package cn.zjitc.exam.controller;

import cn.zjitc.exam.domain.Product;
import cn.zjitc.exam.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "10") int size,
                       Model model) {

        List<Product> products = productService.findByPage(page, size);
        int total = productService.count();
        model.addAttribute("products", products);
        model.addAttribute("page",page);
        model.addAttribute("size", size);
        model.addAttribute("total", total);
        return "product/list";
    }
    @GetMapping("/search")
    public String search(@RequestParam String keyword,
                         @RequestParam(defaultValue = "1") int page,
                         @RequestParam(defaultValue = "10") int size,
                         Model model) {

        int offset = (page - 1) * size;
        List<Product> products = productService.search(keyword, offset, size);
        int total = productService.countByKeyword(keyword);
        model.addAttribute("products", products);
        model.addAttribute("page", page);
        model.addAttribute("size", size);
        model.addAttribute("total", total);
        model.addAttribute("keyword", keyword);

        return "product/list";
    }
    @GetMapping("/add")
    public String addPage() {
        return "product/add";
    }

    // 新增
    @PostMapping("/add")
    public String add(Product product) {
        productService.save(product);
        return "redirect:/product/list";
    }

    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        model.addAttribute("product", productService.findById(id));
        return "product/edit";
    }

    @PostMapping("/edit")
    public String edit(Product product) {
        productService.update(product);
        return "redirect:/product/list";
    }

    @PostMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        productService.delete(id);
        return "redirect:/product/list";
    }

}